'use strict';

angular.module('voteWithAuthApp')
  .controller('AdminCtrl', function($scope, $http, Auth, User) {
    // Use the User $resource to fetch all users
    $scope.users = User.query();
  })
  .controller('MeetingListCtrl', function($scope, $http, socket) {
    $scope.meetings = [];

    $http.get('/api/meetings').success(function(meetings) {
      $scope.meetings = meetings;
      socket.syncUpdates('meeting', $scope.meetings);
    });

    $scope.$on('$destroy', function() {
      socket.unsyncUpdates('meeting');
    });

  })
  .controller('MeetingDetailCtrl', function($scope, $http, socket, $stateParams) {
    $scope.meetings = [];
    $scope.votes = [];
    $scope.loadVote = false;

    $http.get('/api/meetings/' + $stateParams.meetingId).success(function(meetings) {
      $scope.meetings = meetings;
      socket.syncUpdates('meeting', $scope.meetings);
    });

    $http.get('/api/meetings/' + $stateParams.meetingId + '/votes').success(function(votes) {
      $scope.votes = votes;
      socket.syncUpdates('vote', $scope.votes);
    });

    $scope.createVote = function() {
      var newVote = {
        _meetingId: $stateParams.meetingId,
        title: $scope.voteTitle
      };
      $http.post('/api/votes', newVote);
      $scope.voteTitle = '';
    };

    $scope.startMeeting = function() {
      $http.post('/api/meetings/' + $stateParams.meetingId + '/start').success(function(meeting) {
        $scope.meeting = meeting;
      });
    };

    $scope.endMeeting = function() {
      $http.post('/api/meetings/' + $stateParams.meetingId + '/end').success(function(meeting) {
        $scope.meeting = meeting;
      });
    };

    $scope.startVote = function(voteId) {
      if (confirm('您确定要开始投票吗')) {
        $http.post('/api/votes/' + voteId + '/start').success(function() {
          console.log('start...');
        });
      } else {
        return false;
      }
    };

    $scope.cancelVote = function(voteId) {
      if (confirm('您确定要取消投票吗')) {
        $http.post('/api/votes/' + voteId + '/cancel').success(function() {
          console.log('cancel...');
        });
      } else {
        return false;
      }
    };

    $scope.endVote = function(voteId) {
      if (confirm('您确定要结束投票吗')) {
        $http.post('/api/votes/' + voteId + '/end').success(function() {
          console.log('end...');
        });
      } else {
        return false;
      }
    };

    $scope.$on('$destroy', function() {
      socket.unsyncUpdates('meeting');
    });

  })
  .controller('MeetingAddCtrl', function($scope, $http, socket, $state) {
    $scope.meeting = {};
    $scope.createMeeting = function() {
      $http.post('/api/meetings', $scope.meeting);
      $scope.meeting = {};
      $state.go('admin.meeting-list');
    };

    $scope.$on('$destroy', function() {
      socket.unsyncUpdates('meeting');
      socket.unsyncUpdates('vote');
    });
  });;
